package lyx.game
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	
	import lyx.game.control.KeyBoardController;
	import lyx.game.view.WorldView;

	[SWF(width=640,height=480)]
	/**
	 * 程序入口类，负责组建程序各个重要部件。
	 * 程序主视图被加载到stage后，会按照
	 * <p/>
	 * initStage()
	 * <p/>
	 * initializeView()
	 * <p/>
	 * initializeEngine()
	 * <p/>
	 * initializeController()
	 * <p/>
	 * 的顺序对游戏进行初始化
	 */
	public class GameFramework extends Sprite
	{
		protected var _world:WorldView;
		protected var _engine:GameEngine;
		protected var _keyboard_controller:KeyBoardController;
		
		static private var _instance:GameFramework;
		
		static public function getInstance():GameFramework
		{
			if(_instance==null)
			{
				_instance = new GameFramework();
			}
			return _instance;
		}
		
		/**
		 * 程序入口函数
		 */
		public function GameFramework()
		{
			if(_instance==null)
			{
				_instance = this;
			}
			addEventListener(Event.ADDED_TO_STAGE,addToStage);
		}
		
		public function get keyboard_controller():KeyBoardController
		{
			return _keyboard_controller;
		}

		public function get engine():GameEngine
		{
			return _engine;
		}

		public function get world():WorldView
		{
			return _world;
		}

		/**
		 * addToStage()方法，Main被添加进舞台后备调用，在此函数中对各个重要类进行初始化。
		 */
		private function addToStage(event:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE,addToStage);
			initStage();
			initializeView();
			initializeController();
			initializeEngine();
		}
		
		/**
		 * 初始化stage
		 */
		protected function initStage():void
		{
			stage.frameRate = 30;
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
		}
		
		/**
		 * 初始化程序视图
		 */
		protected function initializeView(view:WorldView=null):void
		{
			_world = view ? view : new WorldView();
			addChild(world);
		}
		
		/**
		 * 初始化Controller类
		 */
		protected function initializeController(controller:KeyBoardController=null):void
		{
			_keyboard_controller = controller? controller : new KeyBoardController();
			_keyboard_controller.registerController(stage);
		}
		
		/**
		 * 初始化游戏引擎
		 */
		protected function initializeEngine(engine:GameEngine=null):void
		{
			_engine = engine? engine : new GameEngine();
			_keyboard_controller.addTarget(_engine);
			_engine.start();
		}
	}
}